package com.youku.component;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.youku.component.script.Job;

public abstract class BaseAttribute implements Runnable {

	protected String id;

	/**
	 * 启动执行
	 */
	private Job setup;

	/**
	 * 结束执行
	 */
	private Job teardown;

	private Map<String, Step> stepWithKey = new HashMap<>();

	protected List<Step> stepList = new LinkedList<>();

	public void setup() {
		if (setup != null)
			setup.execute();
	}

	public void teardown() {
		if (teardown != null)
			teardown.execute();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Job getSetup() {
		return setup;
	}

	public void setSetup(String script) {
		if (!StringUtils.isBlank(script)) {
			this.setup = new Job(script);
		}
	}

	public void setTeardown(String script) {
		if (!StringUtils.isBlank(script)) {
			this.teardown = new Job(script);
		}
	}

	public void invokeSetup(boolean invoke) {
		if (!invoke)
			setup = null;
	}

	public void invokeTeardown(boolean invoke) {
		if (!invoke)
			teardown = null;
	}

	public Job getTeardown() {
		return teardown;
	}

	public void addStep(String key, Step step) {
		if (key != null) {
			stepWithKey.put(key, step);
		}
		stepList.add(step);
	}

	public Step getStepWithKey(String key) {
		return stepWithKey.get(key);
	}

	public Map<String, Step> getStepsWithKey() {
		return stepWithKey;
	}

	public List<Step> getStepList() {
		return stepList;
	}

	public void setStepList(List<Step> stepList) {
		this.stepList = stepList;
	}

	public void setStepsWithKey(Map<String, Step> stepWithKey) {
		this.stepWithKey = stepWithKey;
	}

	@Override
	public void run() {
		setup();

		execute();

		teardown();
	}

	private void execute() {
		for (Step step : stepList) {
			step.run();
		}

	}

	public abstract String getProjectId();

	public abstract void addVariable(String key, Object value);

	public abstract String getCaseId();

	public abstract String getSuiteId();

}
